/**
 * 根据响应头判断是否为真正的m3u8链接
 * content-type: application/vnd.apple.mpegurl
 * content-lenght 大于 300
 */
function isRealM3u8Header(responseHeaders) {
  const MinContentLength = 300
  let contentTypeFlag = responseHeaders.some(
    ({ name, value }) => name.toLowerCase() === 'content-type' && value.toLowerCase().includes('application/vnd.apple.mpegurl'),
  )
  let contentLengthFlag = responseHeaders.some(({ name, value }) => name.toLowerCase() === 'content-length' && parseInt(value) > MinContentLength)
  return contentTypeFlag && contentLengthFlag
}

chrome.webRequest.onCompleted.addListener(
  function (details) {
    const url = details.url
    if (!url.includes('.m3u8') || !isRealM3u8Header(details.responseHeaders)) return
    console.log('details', details)
    const tabId = details.tabId

    // 获取当前活动标签页的标题
    chrome.tabs.query({}, function (tabs) {
      let { title } = tabs.find(({ id }) => id === tabId) || { title: '' }

      // 发送通知
      chrome.notifications.create(
        {
          type: 'basic',
          iconUrl: 'assets/logo.png',
          title: '发现m3u8链接',
          message: title,
          contextMessage: url,
          buttons: [{ title: '下载' }],
          priority: 2,
        },
        function (notificationId) {
          // 监听通知按钮点击事件
          chrome.notifications.onButtonClicked.addListener(function (clickedNotificationId, buttonIndex) {
            if (clickedNotificationId === notificationId && buttonIndex === 0) {
              const m3u8Url = `m3u8Download://${url}`
              chrome.tabs.create({ url: m3u8Url })
              copyToClipboard(tabId, title)
              chrome.notifications.clear(clickedNotificationId)
            }
          })
        },
      )
    })
  },
  { urls: ['<all_urls>'] },
  ['responseHeaders'],
)

/**
 * 添加文本到粘贴板中
 * 官方文档的offscreen示例也是通过document.execCommand去执行复制操作。故直接往网页插入代码执行，就不适用offscreen了
 * 官方示例示例地址：https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/cookbook.offscreen-clipboard-write
 */
async function copyToClipboard(tabId, text) {
  await chrome.scripting.executeScript({
    target: { tabId },
    func: (textToCopy) => {
      document.execCommand && useExecCommand(textToCopy)

      function useExecCommand(text) {
        console.log('copy by document.execCommand', text)
        var textArea = document.createElement('textarea')
        textArea.value = text
        // 避免滚动到页面顶部
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        try {
          document.execCommand('copy')
          console.log('已复制到剪贴板:', text)
        } catch (err) {
          console.error('复制失败:', err)
        }

        document.body.removeChild(textArea)
      }
    },
    args: [text], // 传递参数
  })
}
